package com.tusuo.stds.ui.name;

import android.content.Context;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.ApiResult;
import com.tusuo.stds.util.Utils;

import org.androidannotations.annotations.res.StringRes;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;
import timber.log.Timber;

/**
 * @author J.Huang
 * @version 1.0
 *
 */

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(SetNamePresenter.class)
class SetNamePresenter extends MvpBasePresenter<SetNameView> {

    @Inject
    ApiHelper mApiHelper;

    private Context mContext;
    private String mErrMsgServer;

    private Subscriber<ApiResult> mSetNameSubscriber = null;

    SetNamePresenter(Context context) {
        mContext = context;
        mErrMsgServer = mContext.getResources().getString(R.string.err_msg_server);

        Injector.initSetNamePresenterComponent().inject(this);
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (mSetNameSubscriber != null) {
            mSetNameSubscriber.unsubscribe();
            mSetNameSubscriber = null;
        }
        super.detachView(retainInstance);
    }

    void setName(String name) {
        mSetNameSubscriber = new SetNameSubscriber();
        mApiHelper.setName(mSetNameSubscriber, name);
    }

    private class SetNameSubscriber extends Subscriber<ApiResult> {
        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            Timber.d(e.toString());
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(final ApiResult result) {
            if (result.checkState(mContext)) {
                Utils.UI.showToastShort("设置成功");
                if (getView() != null) {
                    getView().backToMainPage();
                }
            }
        }
    }
}
